<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/05/30 13:00:16 $)
// $RCSfile: functions_news.php,v $ : $Revision: 1.11 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Send a mail to subscribers of given template group
*/
function sendNewsMail($newsid, $fromname, $fromemail)
{
	global $dbCore, $_SWIFT, $template;

	$_news = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."news` AS news LEFT JOIN `". TABLE_PREFIX ."newsdata` AS newsdata ON (news.newsid = newsdata.newsid) WHERE news.newsid = '". intval($newsid) ."';");
	if (empty($_news["newsid"]))
	{
		return false;
	}

	$tgroupid = $_news["tgroupid"];
	$template->assign("news", $_news);
	// Set template group
	$template->setGroup($tgroupid);

	$mailcount = 0;
	$subscriberlist = array();

	require_once ("./includes/functions_mail.php");
	$template->assign("contentshtml", getProcessedHTML($_news["contents"]));
	$template->assign("contentstext", getProcessedText($_news["contents"], iif($_POST["iscontenthtml"]==1, true, false)));

	// We fetch all subscribers if its a public news, otherwise we fetch all the staff members for this.
	if ($_news["newstype"] == SWIFTPUBLIC)
	{
		$dbCore->query("SELECT `email` FROM `". TABLE_PREFIX ."newssubscribers` WHERE `tgroupid` IN ('0', '". intval($tgroupid) ."') AND `validated` = '1';");
	} else {
		$dbCore->query("SELECT `email` FROM `". TABLE_PREFIX ."staff`;");
	}
	$_subscriberlist = array();
	while ($dbCore->nextRecord())
	{
		if (!in_array($dbCore->Record["email"], $_subscriberlist))
		{
			$_subscriberlist[] = $dbCore->Record["email"];
		}
	}

	if (!count($_subscriberlist))
	{
		return false;
	}

	foreach ($_subscriberlist as $key=>$val)
	{
		$mailObj = new SWIFT_Mail();
		$template->assign("email", $val);
		$template->assign("ishtml", false);
		$emailtext = $template->displayTemplate("newsmassmail", TEMPLATE_DB);

		$template->assign("ishtml", true);
		$emailhtml = $template->displayTemplate("newsmassmail", TEMPLATE_DB);

		$mailObj->setSubject($_news["emailsubject"]);
		$mailObj->setData($emailhtml, $emailtext, iif($_POST["iscontenthtml"]==1, true, false));

		$mailObj->sendMail(array($val), iif(empty($fromemail), $_SWIFT["settings"]["general_returnemail"], $fromemail), iif(empty($fromname), $_SWIFT["staff"]["fullname"], $fromname), true);

		$subscriberlist[] = $val;
		$mailcount++;
	}

	if (!count($subscriberlist))
	{
		return false;
	}

	return $mailcount;

}

/**
* Insert a new news item
*/
function insertNews($subject, $emailsubject, $description, $tgroupid, $expiry, $newstype, $contents, $sendemail = true, $fromname = "", $fromemail = "")
{
	global $dbCore, $_SWIFT, $template;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."news` (`tgroupid`, `staffid`, `newstype`, `subject`, `emailsubject`, `description`, `dateline`, `expiry`, `edited`, `editedstaffid`, `editeddateline`) VALUES ('". intval($tgroupid) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($newstype) ."', '". $dbCore->escape($subject) ."', '". $dbCore->escape($emailsubject) ."', '". $dbCore->escape($description) ."', '". DATENOW ."', '". intval($expiry) ."', '0', '0', '0');");
	$newsid = $dbCore->lastInsertId();
	if (!$newsid)
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."newsdata` (`newsid`, `contents`) VALUES ('". intval($newsid) ."', '". $dbCore->escape($contents) ."');");

	if ($sendemail)
	{
		sendNewsMail($newsid, $fromname, $fromemail);
	}

	return true;
}

/**
* Update existing news item
*/
function updateNews($newsid, $subject, $emailsubject, $description, $tgroupid, $expiry, $newstype, $contents, $sendemail = true, $fromname = "", $fromemail = "")
{
	global $dbCore, $_SWIFT, $template;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."news` SET `tgroupid` = '". intval($tgroupid) ."', `newstype` = '". $dbCore->escape($newstype) ."', `subject` = '". $dbCore->escape($subject) ."', `emailsubject` = '". $dbCore->escape($emailsubject) ."', `description` = '". $dbCore->escape($description) ."', `expiry` = '". intval($expiry) ."', `edited` = '1', `editedstaffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `editeddateline` = '". DATENOW ."' WHERE `newsid` = '". intval($newsid) ."';");

	$dbCore->query("UPDATE `". TABLE_PREFIX ."newsdata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE `newsid` = '". intval($newsid) ."';");

	if ($sendemail)
	{
		sendNewsMail($newsid, $fromname, $fromemail);
	}

	return true;
}

/**
* Delete the given news
*/
function deleteNews($newsidlist)
{
	global $dbCore;

	if (!_is_array($newsidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."news` WHERE `newsid` IN (". buildIN($newsidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."newsdata` WHERE `newsid` IN (". buildIN($newsidlist) .");");

	return true;
}

/**
* Render the News INSERT/EDIT Form
*/
function renderNewsForm($type)
{
	global $dbCore, $_SWIFT;


	printFormStart();
	printMainTableHeader($_SWIFT["language"]["newsdetails"]);

	// Subject
	printTextRow("subject", $_SWIFT["language"]["newssubject"], $_SWIFT["language"]["desc_newssubject"], "text", $_POST["subject"], 60);

	// Description
	printTextareaRow("description", $_SWIFT["language"]["newsdescription"], $_SWIFT["language"]["desc_newsdescription"], $_POST["description"], 57);

	if ($type == EDIT)
	{
		$newstype = iif($_POST["newstype"]==SWIFTPUBLIC, true, false);
	} else {
		$newstype = true;
	}
	// News Type
	printPublicPrivateRow("newstype", $_SWIFT["language"]["newstype"], $_SWIFT["language"]["desc_newstype"], $newstype);

	// Expiry
	if ($type == EDIT && !empty($_POST["expiry"]))
	{
		$expirytimeline = date("d/m/Y", $_POST["expiry"]);
	}
	printDateRow("expiry", $_SWIFT["language"]["newsformexpiry"], $_SWIFT["language"]["desc_newsformexpiry"], $expirytimeline);

	// Contents
	printhtmlAreaRow("contents", $_SWIFT["language"]["contents"], $_POST["contents"], 25, iif($_SWIFT["settings"]["nw_wysiwyg"]=="1", "1", "0"));

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertnews"], $_SWIFT["language"]["updatenews"]));

	printMainTableFooter();

	echo "<BR />";
	printMainTableHeader($_SWIFT["language"]["newsoptions"]);
	printYesNoRow("sendemail", $_SWIFT["language"]["sendemail"], $_SWIFT["language"]["desc_sendemail"], iif($type==INSERT, true, false));

	if ($type == EDIT)
	{
		if (substr($_POST["emailsubject"], 0, strlen($_SWIFT["language"]["updateprefix"])) != $_SWIFT["language"]["updateprefix"])
		{
			$emailsubject = $_SWIFT["language"]["updateprefix"].$_POST["emailsubject"];
		} else {
			$emailsubject = $_POST["emailsubject"];
		}
	}

	printTextRow("emailsubject", $_SWIFT["language"]["emailsubject"], $_SWIFT["language"]["desc_emailsubject"], "text", $emailsubject, 60);
	printTextRow("fromname", $_SWIFT["language"]["fromname"], $_SWIFT["language"]["desc_fromname"], "text", $_SWIFT["staff"]["fullname"]);
	printTextRow("fromemail", $_SWIFT["language"]["fromemail"], $_SWIFT["language"]["desc_fromemail"], "text", $_SWIFT["settings"]["general_returnemail"]);

	$_options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templategroups` ORDER BY `tgroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$_options[$index]["title"] = $dbCore->Record["title"];
		$_options[$index]["value"] = $dbCore->Record["tgroupid"];
		if (($_POST["tgroupid"] == $dbCore->Record["tgroupid"] && $type == EDIT) || ($dbCore->Record["isdefault"] == 1 && $type == INSERT))
		{
			$_options[$index]["selected"] = true;
		}
		$index++;
	}
	printSelectRow("tgroupid", $_SWIFT["language"]["newstgroup"], $_SWIFT["language"]["desc_newstgroup"], $_options);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertnews"], $_SWIFT["language"]["updatenews"]));

	printMainTableFooter();


	addHiddenField("_m", "news");
	addHiddenField("_a", iif($type==INSERT, "insertnews", "editnews"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("newsid", $_POST["newsid"]);
	}


	printFormEnd();
}

/**
* Converts the news item into PDF
*/
function makeNewsPDF($newsid, $isstaffcp = false)
{
	global $dbCore, $_SWIFT, $template;

	$_news = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."news` AS news LEFT JOIN `". TABLE_PREFIX ."newsdata` AS newsdata ON (news.newsid = newsdata.newsid) WHERE news.newsid = '". intval($_REQUEST["newsid"]) ."';");
	if (empty($_news["newsid"]) && ($isstaffcp == false && $_news["newstype"] == SWIFTPRIVATE))
	{
		return false;
	}

	$_news["contents"] = getProcessedHTML($_news["contents"]);
	$_news["description"] = getProcessedHTML($_news["description"]);
	$_news["fullname"] = $_SWIFT["staffcache"][$_news["staffid"]]["fullname"];
	$_news["dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_news["dateline"]);

	$htmloutput = $_news["description"]."<BR /><BR />".$_news["contents"];
	$str=array(
		'<br />' => '<br>',
		'<hr />' => '<hr>',
		'[r]' => '<red>',
		'[/r]' => '</red>',
		'[l]' => '<blue>',
		'[/l]' => '</blue>',
		'&#8220;' => '"',
		'&#8221;' => '"',
		'&#8222;' => '"',
		'&#8230;' => '...',
		'&#8217;' => '\''
	);
	foreach ($str as $_from => $_to) $htmloutput = str_replace($_from,$_to,$htmloutput);

	require_once ("./includes/functions_pdf.php");
	$pdf = new PDF('P','mm','A4',"",$_SWIFT["swiftpath"]."index.php?_m=news&_a=viewnews&newsid=".$_news["newsid"],false);
	$pdf->Open();
	$pdf->SetCompression(true);
	$pdf->SetCreator(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
	$pdf->SetDisplayMode('real');
	$pdf->SetTitle(_iso2ascii($_news["subject"]));
	$pdf->SetAuthor(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
	$pdf->AddPage();

	$pdf->PutMainTitle(_iso2ascii($_news["subject"]));
	$pdf->PutMinorHeading(_iso2ascii($_SWIFT["language"]["nwauthor"]));
	$pdf->PutMinorTitle(_iso2ascii($_SWIFT["settings"]["general_companyname"]));
	$pdf->PutMinorHeading(_iso2ascii($_SWIFT["language"]["nwcreatedon"]).$_news["dateline"]);
	$pdf->PutLine();

	$pdf->WriteHTML($htmloutput, $htmloutput);

	$pdf->Output(cleanVar(str_replace(" ", "_", $_news["subject"])).".pdf", "D");

	return true;
}
?>